package com.alibaba.web.config;

import com.alibaba.api.pojos.User;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class MyTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            if (((HandlerMethod) handler).hasMethodAnnotation(NoToken.class)) {
                return true;
            }
        }

        String token = request.getHeader("Authorization");

        User user = par(token);
        if (user != null) {
            UserThreadLocal.set(user);
            return true;
        }

        //无权限访问
        response.setStatus(600);
        return false;
    }

    public User par(String token) {
        Map<String, Object> body = Jwts.parser().setSigningKey("secret").parseClaimsJws(token).getBody();
        User user = new User();
        user.setId(Integer.parseInt(body.get("id").toString()));
        user.setAccountId(Long.valueOf(body.get("accountId").toString()));

        return user;
    }
}
